<?php

namespace App\Service\Cashbook;


use App\Enums\BaseErrorCode;
use App\Exceptions\Custom\ResponseHttpException;
use App\Library\Rms\RmsShopApi;
use App\Models\Cashbook\CashbookBillSyncSwitchModel;
use App\Models\Cashbook\CashbookCycleModel;
use App\Models\Cashbook\CashbookModel;
use App\Models\Common\ResourcesModel;
use App\Remote\Orm\OrmNewOrderRemote;
use App\Service\BaseService;
use App\Service\OpenShop\User\RmsUserService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Redis;

class CashbookService
{
    /**
     * 总览
     * @param $userId
     * @param $shopId
     * @param $type
     * @param $category
     * @param $startTime
     * @param $endTime
     * @return array
     * @throws GuzzleException
     */
    public static function total($userId, $shopId, $type, $category, $startTime, $endTime): array
    {
        $totalAmount = CashbookModel::getTotalAmount($shopId, $userId, $type, $category, $startTime, $endTime);//总数
        $total = CashbookModel::query()
            ->where('shopId', $shopId)
            ->when(
                $userId !== "" && is_array($userId), function ($query) use ($userId) {
                $query->whereIn('userId', $userId);
            }
            )
            ->when(
                $type, function ($query) use ($type) {
                $query->where('type', $type);
            }
            )
            ->when(
                $category && is_array($category), function ($query) use ($category) {
                $query->whereIn('category', $category);
            }
            )
            ->when(
                $startTime && $endTime, function ($query) use ($startTime, $endTime) {
                $query->whereBetween('recordTime', [strtotime($startTime), strtotime($endTime) + 86399]);
            }
            )
            ->groupBy('category')
            ->selectRaw('type,category,sum(amount) totalAmount')
            ->get()
            ->map(
                function ($cashbookModel) use ($totalAmount) {
                    return [
                        'type'         => $cashbookModel->type,
                        'typeText'     => CashbookModel::TYPE_TEXT_MAPPING[$cashbookModel->type] ?? "",
                        'category'     => $cashbookModel->category,
                        'categoryText' => CashbookModel::CATEGORY_TEXT_MAPPING_ALL[$cashbookModel->category] ?? "",
                        'amount'       => bcdiv100($cashbookModel->totalAmount),
                        'ratio'        => BaseService::formatPercent($cashbookModel->totalAmount, $totalAmount),//占比
                    ];
                }
            )->toArray();

        //查询当前门店员工信息
        $staffData      = (new RmsShopApi())->getShopStaffListByShopId($shopId, false, true)['data']['list'] ?? [];
        $staffMapText   = collect($staffData)->map(
            function ($staff) {
                return [
                    'key'   => $staff['username'],
                    'value' => $staff['id'],
                ];
            }
        )->toArray();
        $staffMapText[] = [
            'key'   => '门店账户',
            'value' => 0,
        ];
        //查询该店铺是否操作过账单同步开关
        $billSyncSwitchCount = CashbookBillSyncSwitchModel::query()->where('shopId', $shopId)->count();
        $setnxRes            = 0;
        if (!$billSyncSwitchCount) {//未打开同步开关 每天提醒一次
            $redisKey = sprintf('tiger:cashbook:isFirstDate:%s:%s', date('Ymd'), $shopId);
            $setnxRes = Redis::setnx($redisKey, 1);
            if ($setnxRes) {
                Redis::expire($redisKey, 86401);
            }
        }

        return [
            'total'                 => $total,
            'typeMapText'           => enumToSelection(CashbookModel::TYPE_TEXT_MAPPING),
            'categoryIncomeMapText' => enumToSelection(CashbookModel::CATEGORY_TEXT_MAPPING_INCOME),
            'categoryPayMapText'    => enumToSelection(CashbookModel::CATEGORY_TEXT_MAPPING_PAY),
            'staffMapText'          => $staffMapText,
            'isFirst'               => $setnxRes && $billSyncSwitchCount == 0,//首次返回true,前端使用
        ];
    }

    /**
     * 列表
     * @param $userId
     * @param $shopId
     * @param $type
     * @param $category
     * @param $startTime
     * @param $endTime
     * @param $pageNum
     * @param $pageSize
     * @return array
     * @throws GuzzleException
     */
    public static function lists($userId, $shopId, $type, $category, $startTime, $endTime, $pageNum, $pageSize): array
    {
        $paginator = CashbookModel::query()
            ->where('shopId', $shopId)
            ->when(
                $userId !== "" && is_array($userId), function ($query) use ($userId) {
                $query->whereIn('userId', $userId);
            }
            )
            ->when(
                $type, function ($query) use ($type) {
                $query->where('type', $type);
            }
            )
            ->when(
                $category && is_array($category), function ($query) use ($category) {
                $query->whereIn('category', $category);
            }
            )
            ->when(
                $startTime && $endTime, function ($query) use ($startTime, $endTime) {
                $query->whereBetween('recordTime', [strtotime($startTime), strtotime($endTime) + 86399]);
            }
            )
            ->orderByDesc('recordTime')
            ->orderByDesc('createdAt')
            ->orderByDesc('createdAt')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        //门店信息
        $shopIds   = collect($paginator->items())->pluck('shopId')->toArray();
        $shopInfo = (new RmsShopApi())->getShopByIds($shopIds, ['id', 'shopCode', 'name'])['data']['shopList'] ?? [];
        $shopList = array_column($shopInfo, null, 'id');
        //用户信息
        $userIds   = collect($paginator->items())->pluck('userId')->toArray();
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($userIds)['data'])->keyBy('id');

        $totalIncomeAmountList = CashbookModel::getTotalAmount($shopId, $userId, CashbookModel::TYPE_INCOME, $category, $startTime, $endTime, true);//收入总数
        $totalPayAmountList    = CashbookModel::getTotalAmount($shopId, $userId, CashbookModel::TYPE_PAY, $category, $startTime, $endTime, true);   //支出总数
        $totalIncomeAmount     = $totalPayAmount = 0;
        if ($totalIncomeAmountList) {
            $totalIncomeAmountList = $totalIncomeAmountList->keyBy('day')->toArray();
            $totalIncomeAmount     = array_sum(array_column($totalIncomeAmountList, 'totalAmount'));
        }
        if ($totalPayAmountList) {
            $totalPayAmountList = $totalPayAmountList->keyBy('day')->toArray();
            $totalPayAmount     = array_sum(array_column($totalPayAmountList, 'totalAmount'));
        }

        $total             = [
            'totalIncomeAmount' => bcdiv100($totalIncomeAmount),
            'totalPayAmount'    => bcdiv100($totalPayAmount),
        ];
        $lists     = $paginator->map(
            function (CashbookModel $cashbookModel) use ($totalPayAmountList, $totalIncomeAmountList, $userInfos, $shopList) {
                $recordTime        = $cashbookModel->recordTime ? date('Y-m-d', $cashbookModel->recordTime) : '';
                $totalIncomeAmount = $totalPayAmount = 0;
                if (isset($totalIncomeAmountList[$recordTime]['totalAmount']) && $totalIncomeAmountList[$recordTime]['totalAmount']) {
                    $totalIncomeAmount = bcdiv100($totalIncomeAmountList[$recordTime]['totalAmount']);
                }
                if (isset($totalPayAmountList[$recordTime]['totalAmount']) && $totalPayAmountList[$recordTime]['totalAmount']) {
                    $totalPayAmount = bcdiv100($totalPayAmountList[$recordTime]['totalAmount']);
                }
                return [
                    'id'                => $cashbookModel->id,
                    'shopId'            => $cashbookModel->shopId,
                    'shopCode'          => $shopList[$cashbookModel->shopId]['shopCode'] ?? '-',
                    'shopName'          => $shopList[$cashbookModel->shopId]['name'] ?? '-',
                    'recordTime'        => $recordTime,
                    'manageName'        => $userInfos[$cashbookModel->userId]['username'] ?? '门店账户',
                    'amount'            => bcdiv100($cashbookModel->amount),
                    'type'              => $cashbookModel->type,
                    'typeText'          => CashbookModel::TYPE_TEXT_MAPPING[$cashbookModel->type] ?? "",
                    'category'          => $cashbookModel->category,
                    'categoryText'      => CashbookModel::CATEGORY_TEXT_MAPPING_ALL[$cashbookModel->category] ?? "",
                    'source'            => $cashbookModel->source,
                    'sourceText'        => CashbookModel::SOURCE_TEXT_MAPPING[$cashbookModel->source] ?? "",
                    'orderId'           => $cashbookModel->orderId,
                    'remark'            => $cashbookModel->remark,
                    'totalIncomeAmount' => $totalIncomeAmount,
                    'totalPayAmount'    => $totalPayAmount,
                ];
            }
        );
        return [
            'pageNum'   => $paginator->currentPage(),
            'pageSize'  => $paginator->perPage(),
            'pageCount' => ceil($paginator->total() / $paginator->perPage()),
            'count'     => $paginator->total(),
            'lists'     => $lists,
            'total'     => $total,
        ];
    }

    /**
     * 详情
     * @param $shopId
     * @param $id
     * @return array
     * @throws GuzzleException
     */
    public static function detail($shopId, $id): array
    {
        $cashbookModel = CashbookModel::query()
            ->with(['resourcesRel'])
            ->where('shopId', $shopId)
            ->where('id', $id)
            ->get()
            ->first();
        if (!$cashbookModel) {
            return [];
        }
        //门店信息
        $shopInfo = (new RmsShopApi())->getShopByIds([$cashbookModel->shopId], ['id', 'shopCode', 'name'])['data']['shopList'] ?? [];
        $shopList = array_column($shopInfo, null, 'id');
        //用户信息
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds([$cashbookModel->userId])['data'])->keyBy('id');
        //资源数据
        $resourcesList = [];
        collect($cashbookModel->resourcesRel)->each(
            function (ResourcesModel $resourcesModel) use (&$resourcesList) {
                $resourcesList[] = picturePath($resourcesModel->url);
            }
        )->toArray();
        return [
            'id'           => $cashbookModel->id,
            'shopId'       => $cashbookModel->shopId,
            'shopCode'     => $shopList[$cashbookModel->shopId]['shopCode'] ?? '-',
            'shopName'     => $shopList[$cashbookModel->shopId]['name'] ?? '-',
            'recordTime'   => $cashbookModel->recordTime ? date('Y-m-d', $cashbookModel->recordTime) : '',
            'manageName'   => $userInfos[$cashbookModel->userId]['username'] ?? '门店账户',
            'manageMobile' => $userInfos[$cashbookModel->userId]['mobile'] ?? '',
            'amount'       => bcdiv100($cashbookModel->amount),
            'type'         => $cashbookModel->type,
            'typeText'     => CashbookModel::TYPE_TEXT_MAPPING[$cashbookModel->type] ?? "",
            'category'     => $cashbookModel->category,
            'categoryText' => CashbookModel::CATEGORY_TEXT_MAPPING_ALL[$cashbookModel->category] ?? "",
            'source'       => $cashbookModel->source,
            'sourceText'   => CashbookModel::SOURCE_TEXT_MAPPING[$cashbookModel->source] ?? "",
            'isEdit'       => $cashbookModel->source == CashbookModel::SOURCE_SYSTEM_ADD ? 0 : 1,//是否能修改内容 1-可以
            'img'          => $resourcesList,
            'orderId'      => $cashbookModel->orderId,
            'remark'       => $cashbookModel->remark,
        ];
    }

    /**
     * 记一笔
     * @param $shopId
     * @param $type
     * @param $date
     * @param $category
     * @param $amount
     * @param $remark
     * @param $img
     * @param $userId
     * @param int $source
     */
    public static function add($shopId, $type, $date, $category, $amount, $remark, $img, $userId, $source = CashbookModel::SOURCE_ADD)
    {
        try {
            $amount = $amount * 100;
            if ($type == CashbookModel::TYPE_PAY) {//支出 显示负数
                $amount = '-' . $amount;
            }
            $createData =
                [
                    'shopId'     => $shopId,
                    'userId'     => $userId,
                    'recordTime' => strtotime($date),
                    'type'       => $type,
                    'category'   => $category,
                    'source'     => $source,
                    'amount'     => $amount,
                    'remark'     => $remark,
                ];
            $cashbookModel = CashbookModel::insertData($createData);
            if ($cashbookModel) {
                if ($img && is_array($img)) {//资源保存
                    foreach ($img as $file) {
                        ResourcesModel::moduleBusinessResourcesBuild(
                            ResourcesModel::MODULE_TYPE_CASHBOOK_ADD,
                            ResourcesModel::BUSINESS_CASHBOOK_ADD,
                            'cashbookImg',
                            (int)$cashbookModel->id,
                            ltrim(parse_url($file, PHP_URL_PATH), '/')
                        );
                    }
                    ResourcesModel::moduleBusinessResourcesSave();
                }
            }
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "记账本添加记录失败");
        }
    }

    /**
     * 编辑
     * @param $shopId
     * @param $id
     * @param $date
     * @param $type
     * @param $category
     * @param $amount
     * @param $remark
     * @param $img
     * @param $userId
     */
    public static function update($shopId, $id, $date, $type, $category, $amount, $remark, $img, $userId)
    {
        $cashbookModel = CashbookModel::query()
            ->where('shopId', $shopId)
            ->where('id', $id)
            ->get()
            ->first();
        if (!$cashbookModel) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
        }
        $updateData = [];
        if ($date) {
            $updateData['recordTime'] = strtotime($date);
        }
        if ($type) {
            $updateData['type'] = $type;
        }
        if ($category) {
            $updateData['category'] = $category;
        }
        if ($amount) {
            $amount = $amount * 100;
            if ((isset($type) && $type == CashbookModel::TYPE_PAY)) {//支出 显示负数
                $amount = '-' . $amount;
            }
            $updateData['amount'] = $amount;
        }
        if ($remark) {
            $updateData['remark'] = $remark;
        }
        try {
            if ($updateData) {
                $updateData['updatedByUid'] = $userId;
                CashbookModel::query()->where('id', $id)->update($updateData);
            }
            if ($img && is_array($img)) {//资源保存
                $resources = ['cashbookImg' => $img];
                ResourcesModel::moduleBusinessResourcesUpdate(
                    $resources,
                    ResourcesModel::MODULE_TYPE_CASHBOOK_ADD,
                    ResourcesModel::BUSINESS_CASHBOOK_ADD,
                    $id,
                );
            } else {//删除之前的数据
                ResourcesModel::query()->where("module", ResourcesModel::MODULE_TYPE_CASHBOOK_ADD)
                    ->where("business", ResourcesModel::BUSINESS_CASHBOOK_ADD)
                    ->where("businessId", $id)
                    ->update(["isDeleted" => 1]);
            }
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "记账本修改记录失败");
        }
    }

    /**
     * 删除
     * @param $shopId
     * @param $id
     * @param $userId
     */
    public static function delete($shopId, $id, $userId)
    {
        $cashbookModel = CashbookModel::query()
            ->where('shopId', $shopId)
            ->where('id', $id)
            ->whereIn('source', [CashbookModel::SOURCE_ADD, CashbookModel::SOURCE_PERIOD_SYNC_ADD])
            ->get()
            ->first();
        if (!$cashbookModel) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
        }
        try {
            CashbookModel::query()->where('id', $id)->update(['isDeleted' => 1, 'updatedByUid' => $userId]);
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "记账本删除记录失败");
        }
    }

    /**
     * 同步开关列表
     * @param $shopId
     * @return array[]
     */
    public static function switchList($shopId): array
    {
        $switchData = CashbookBillSyncSwitchModel::getSwitchData($shopId);
        if ($switchData && count($switchData)) {
            $switchData = collect($switchData)->keyBy('type')->toArray();
        } else {
            $switchData = [];
        }
        $data = [];
        foreach (CashbookBillSyncSwitchModel::TYPE_TEXT_MAPPING as $k => $v) {
            $type   = $switchData[$k]['type'] ?? $k;
            $data[] = [
                'id'       => $switchData[$k]['id'] ?? 0,
                'type'     => $type,
                'typeText' => CashbookBillSyncSwitchModel::TYPE_TEXT_MAPPING[$type] ?? "",
                'switch'   => $switchData[$k]['switch'] ?? CashbookBillSyncSwitchModel::SWITCH_OFF,
            ];
        }
        return $data;
    }

    /**
     * 同步开关编辑
     * @param $shopId
     * @param $data
     * @param $userId
     */
    public static function switchUpdate($shopId, $data, $userId)
    {
        $createData = [];
        $switchData = CashbookBillSyncSwitchModel::getSwitchData($shopId);
        if ($switchData && count($switchData)) {
            $switchData = collect($switchData)->keyBy('type')->toArray();
            foreach ($data as $v) {
                if (isset($switchData[$v['type']])) {
                    if ($switchData[$v['type']]['type'] == $v['type'] && $switchData[$v['type']]['switch'] != $v['switch']) {
                        CashbookBillSyncSwitchModel::query()->where('id', $switchData[$v['type']]['id'])
                            ->update(['switch' => (int)$v['switch'], 'updatedByUid' => $userId]);
                    }
                } else {
                    if (in_array($v['type'], array_keys(CashbookBillSyncSwitchModel::TYPE_TEXT_MAPPING))) {
                        $createData[] = [
                            'shopId'       => $shopId,
                            'type'         => $v['type'],
                            'switch'       => (int)$v['switch'],
                            'createdAt'    => time(),
                            'createdByUid' => $userId,
                        ];
                    }
                }

            }
        } else {
            foreach ($data as $v) {
                if (in_array($v['type'], array_keys(CashbookBillSyncSwitchModel::TYPE_TEXT_MAPPING))) {
                    $createData[] = [
                        'shopId'       => $shopId,
                        'type'         => $v['type'],
                        'switch'       => (int)$v['switch'],
                        'createdAt'    => time(),
                        'createdByUid' => $userId,
                    ];
                }
            }
        }
        if ($createData) {
            CashbookBillSyncSwitchModel::query()->insert($createData);
        }
    }

    /**
     * 周期记录列表
     * @param $shopId
     * @param $userId
     * @return array
     * @throws GuzzleException
     */
    public static function cycleList($shopId, $userId): array
    {
        $cashbookCycleModel = CashbookCycleModel::query()
            ->where('shopId', $shopId)
//            ->where('userId', $userId)
            ->whereIn('status', [CashbookCycleModel::STATUS_DEAL_ING, CashbookCycleModel::STATUS_PAUSE])
            ->orderByDesc('createdAt')
            ->get();
        if ($cashbookCycleModel) {
            $userIds           = collect($cashbookCycleModel)->pluck('userId')->toArray();
            $userInfos         = collect(RmsUserService::getRmsUserInfoByUserIds($userIds)['data'])->keyBy('id');
            $cycleList['data'] = collect($cashbookCycleModel)->map(
                function ($cashbookCycleModel) use ($userInfos) {
                    $nextDate = $cashbookCycleModel->nextTime ? date('Y-m-d', $cashbookCycleModel->nextTime) : '';
                    return [
                        'id'            => $cashbookCycleModel->id,
                        'shopId'        => $cashbookCycleModel->shopId,
                        'userId'        => $cashbookCycleModel->userId,
                        'userName'      => $userInfos[$cashbookCycleModel->userId]['username'] ?? "",
                        'cycleType'     => $cashbookCycleModel->cycleType,
                        'cycleTypeText' => CashbookCycleModel::CYCLE_TYPE_TEXT_MAPPING[$cashbookCycleModel->cycleType] ?? "",
                        'type'          => $cashbookCycleModel->type,
                        'typeText'      => CashbookModel::TYPE_TEXT_MAPPING[$cashbookCycleModel->type] ?? "",
                        'category'      => $cashbookCycleModel->category,
                        'categoryText'  => CashbookModel::CATEGORY_TEXT_MAPPING_ALL[$cashbookCycleModel->category] ?? "",
                        'amount'        => bcdiv100($cashbookCycleModel->amount),
                        'startTime'     => $cashbookCycleModel->startTime ? date('Y-m-d', $cashbookCycleModel->startTime) : '',
                        'endTime'       => $cashbookCycleModel->endTime ? date('Y-m-d', $cashbookCycleModel->endTime) : '',
                        'nextTime'      => $nextDate == '2099-12-31' ? "永不结束" : $nextDate,
                        'status'        => $cashbookCycleModel->status,
                        'statusText'    => CashbookCycleModel::STATUS_TEXT_MAPPING[$cashbookCycleModel->status] ?? "",
                        'remark'        => $cashbookCycleModel->remark,
                    ];
                }
            )->toArray();
        } else {
            $cycleList['data'] = [];
        }
        $cycleList['cycleTypeMapText'] = enumToSelection(CashbookCycleModel::CYCLE_TYPE_TEXT_MAPPING);
        return $cycleList;
    }

    /**
     * 周期记录详情
     * @param $shopId
     * @param $id
     * @return array
     * @throws GuzzleException
     */
    public static function cycleDetail($shopId, $id): array
    {
        $cashbookCycleModel = CashbookCycleModel::query()
            ->where('shopId', $shopId)
            ->where('id', $id)
            ->get()
            ->first();
        if (!$cashbookCycleModel) {
            return [];
        }
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($cashbookCycleModel->userId)['data'])->keyBy('id');
        $nextDate  = $cashbookCycleModel->nextTime ? date('Y-m-d', $cashbookCycleModel->nextTime) : '';
        return [
            'id'               => $cashbookCycleModel->id,
            'shopId'           => $cashbookCycleModel->shopId,
            'userId'           => $cashbookCycleModel->userId,
            'userName'         => $userInfos[$cashbookCycleModel->userId]['username'] ?? "",
            'userMobile'       => $userInfos[$cashbookCycleModel->userId]['mobile'] ?? "",
            'cycleType'        => $cashbookCycleModel->cycleType,
            'cycleTypeText'    => CashbookCycleModel::CYCLE_TYPE_TEXT_MAPPING[$cashbookCycleModel->cycleType] ?? "",
            'type'             => $cashbookCycleModel->type,
            'typeText'         => CashbookModel::TYPE_TEXT_MAPPING[$cashbookCycleModel->type] ?? "",
            'category'         => $cashbookCycleModel->category,
            'categoryText'     => CashbookModel::CATEGORY_TEXT_MAPPING_ALL[$cashbookCycleModel->category] ?? "",
            'amount'           => bcdiv100($cashbookCycleModel->amount),
            'startTime'        => $cashbookCycleModel->startTime ? date('Y-m-d', $cashbookCycleModel->startTime) : '',
            'endTime'          => $cashbookCycleModel->endTime ? date('Y-m-d', $cashbookCycleModel->endTime) : '',
            'nextTime'         => $nextDate == '2099-12-31' ? "永不结束" : $nextDate,
            'status'           => $cashbookCycleModel->status,
            'statusText'       => CashbookCycleModel::STATUS_TEXT_MAPPING[$cashbookCycleModel->status] ?? "",
            'remark'           => $cashbookCycleModel->remark,
            'cycleTypeMapText' => enumToSelection(CashbookCycleModel::CYCLE_TYPE_TEXT_MAPPING),
        ];
    }

    /**
     * 周期记录编辑
     * @param $shopId
     * @param $userId
     * @param $id
     * @param $cycleType
     * @param $type
     * @param $category
     * @param $remark
     * @param $amount
     * @param $startTime
     * @param $endTime
     */
    public static function cycleUpdate($shopId, $userId, $id, $cycleType, $type, $category, $remark, $amount, $startTime, $endTime)
    {
        if (strtotime($startTime) < strtotime(date('Y-m-d'))) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "开始时间不能小于当前时间");
        }
        $nextData = self::getNextData($startTime, $endTime, $cycleType);//下次开始时间
        if (!$nextData) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "获取下次周期执行时间失败");
        }
        if ($id) {
            $cashbookCycleModel = CashbookCycleModel::query()
                ->where('id', $id)
                ->where('shopId', $shopId)
                ->get();
            if (!$cashbookCycleModel) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
            }
        }
        try {
            $amount = $amount * 100;
            if ($type == CashbookModel::TYPE_PAY) {//支出 显示负数
                $amount = '-' . $amount;
            }
            $createData =
                [
                    'shopId'    => $shopId,
                    'userId'    => $userId,
                    'startTime' => strtotime($startTime),
                    'endTime'   => strtotime($endTime),
                    'nextTime'  => strtotime($nextData),
                    'type'      => $type,
                    'category'  => $category,
                    'amount'    => $amount,
                    'status'    => CashbookCycleModel::STATUS_DEAL_ING,
                    'cycleType' => $cycleType,
                    'remark'    => $remark,
                ];
            if ($id) {
                CashbookCycleModel::query()->where('id', $id)->update($createData);
            } else {
                CashbookCycleModel::insertData($createData);
            }
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "周期记录编辑失败");
        }
    }

    /**
     * 周期记录删除
     * @param $shopId
     * @param $id
     * @param $userId
     */
    public static function cycleDelete($shopId, $id, $userId)
    {
        $cashbookCycleModel = CashbookCycleModel::query()
            ->where('shopId', $shopId)
            ->where('id', $id)
            ->get()
            ->first();
        if (!$cashbookCycleModel) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
        }
        try {
            CashbookCycleModel::query()->where('id', $id)->update(['isDeleted' => 1, 'updatedByUid' => $userId]);
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "周期删除记录失败");
        }
    }

    /**
     * 获取周期下次执行时间
     * @param string $startTime 开始时间
     * @param string $endTime 结束时间
     * @param int $cycleType 周期类型
     * @return false|string
     */
    public static function getNextData(string $startTime, string $endTime, int $cycleType)
    {
        $nextData = '';
        switch ($cycleType) {
            case CashbookCycleModel::CYCLE_TYPE_DAY://每天
                $nextData = date('Y-m-d', strtotime($startTime . "+1 day"));
                break;
            case CashbookCycleModel::CYCLE_TYPE_WEEK://每周
                $nextData = date('Y-m-d', strtotime($startTime . "+1 week"));
                break;
            case CashbookCycleModel::CYCLE_TYPE_MONTH://每月
                $nextData = date('Y-m-d', strtotime($startTime . "+1 month"));
                break;
            case CashbookCycleModel::CYCLE_TYPE_QUARTERLY://每季度
                $nextData = date('Y-m-d', strtotime($startTime . "+3 month"));
                /*$y = date('Y', strtotime($startTime));
                $m = date('m', strtotime($startTime));
                switch ($m) {
                    case 1:
                    case 2:
                    case 3:
                        $nextData = $y . '-04-01';
                        break;
                    case 4:
                    case 5:
                    case 6:
                        $nextData = $y . '-07-01';
                        break;
                    case 7:
                    case 8:
                    case 9:
                        $nextData = $y . '-10-01';
                        break;
                    case 10:
                    case 11:
                    case 12:
                        $nextData = ($y + 1) . '-01-01';
                        break;
                }*/
                break;
            case CashbookCycleModel::CYCLE_TYPE_YEAR://每年
                $nextData = date('Y-m-d', strtotime($startTime . "+1 year"));
                break;
        }
        if ($nextData && strtotime($nextData) > strtotime($endTime)) {
            $nextData = '';//不能大于结束时间
        }
        return $nextData;
    }

    /**
     * 记账本数据手动同步
     * @param $shopId
     * @param $id
     * @param $userId
     * @throws GuzzleException
     */
    public static function manualUpdate($shopId, $id, $userId)
    {
        $cashbookModel = CashbookModel::query()
            ->where('shopId', $shopId)
            ->where('id', $id)
            ->first();
        if (!$cashbookModel) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
        }

        switch ($cashbookModel->category) {
            case CashbookModel::CATEGORY_1://取店铺营业额数据
                $amount = (new RmsShopApi())->originalPrice($shopId, $cashbookModel->recordTime, $cashbookModel->recordTime + 86399)['data']['realPayPrice'] ?? 0;
                if ($amount != $cashbookModel->amount) {
                    $cashbookModel->amount = $amount;
                    $cashbookModel->save();
                }
                break;
            case CashbookModel::CATEGORY_5://自动同步订货账单
                if ($cashbookModel->orderId) {
                    $applyContent = OrmNewOrderRemote::detail($cashbookModel->orderId);//获取订货详情
                    $code         = $applyContent['code'] ?? -1;
                    if ($code == 0) {
                        $applyContent = $applyContent['data'] ?? [];
                        if ($applyContent && $applyContent['pay_amount'] * 100 != abs($cashbookModel->amount)) {
                            $cashbookModel->amount = -$applyContent['pay_amount'] * 100;
                            $cashbookModel->save();
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 判断用户是否在门店中 是-返回true
     * @param $shopId
     * @param $userId
     * @return bool
     * @throws GuzzleException
     */
    public static function isShopStaff($shopId, $userId): bool
    {
        $userIds = collect((new RmsShopApi())->getShopStaffListByShopId($shopId, false, true)['data']['list'] ?? [])
            ->pluck('id')
            ->toArray();
        return in_array($userId, $userIds);
    }
}
